var redis = require('../db/redis')
var pu = require('../tool/public')
var mg = require('../db/userdb')
var ex = require('../tool/excel')

/**
 * @Description: 团队
 * @author longfa liang
 * @date 2021/7/19
 */

class team {
    /*查询组织人员*/
    async find_userinfo (req, res, next) {
        let userid = req.headers.userid
        let team = req.headers.team
        let userinfo = await mg.findOne('team_users', { team_id: mg.ObjectID(team), userid: mg.ObjectID(userid) })
        if (userinfo) {
            delete userinfo.phone
            pu.success('OK', userinfo, res)
            return
        } else {
            pu.fail('ID不正确', res)
        }
    }

    /*修改组织人员*/
    async update_team_user (req, res, next) {
        var role_idlist = req.body.role_idlist //角色列表
        var duties_id = req.body.duties_id //岗位
        var department_id = req.body.department_id //部门
        var name = req.body.name //名称
        var desc = req.body.desc //描述
        var entry_time = req.body.entry_time //入职时间
        var on_the_job = req.body.on_the_job //是否离职
        var job_number = req.body.job_number //工号
        var _idlist = req.body._idlist //工号
        var leader_id = req.body.leader_id //直属领导ID
        var email = req.body.email
        var leader_name = req.body.leader_name //直属领导ID

        let isnull = pu.isnull([_idlist])
        if (isnull) {
            pu.fail('参数不正确', res)
            return
        }
        var update = {}
        if (role_idlist) {
            update.role_idlist = []
            for (var i = 0; i < role_idlist.length; i++) {
                update.role_idlist.push(mg.ObjectID(role_idlist))
            }
        }
        if (duties_id) {
            update.duties_id = mg.ObjectID(duties_id)
        }
        if (department_id) {
            update.department_id = mg.ObjectID(department_id)
        }
        if (name) {
            update.name = name
        }
        if (email) {
            update.email = email
        }
        if (desc) {
            update.desc = desc
        }
        if (entry_time) {
            update.entry_time = entry_time
        }
        if (on_the_job) {
            update.on_the_job = Number(on_the_job)
        }
        if (job_number) {
            update.job_number = job_number
        }
        if (leader_id) {
            update.leader_id = leader_id
        }
        if (leader_name) {
            update.leader_name = leader_name
        }

        if (JSON.stringify(update) == '{}') {
            pu.fail('没有修改信息', res)
            return
        }
        var where = {}
        if (_idlist) {
            where['$or'] = []
            for (var i = 0; i < _idlist.length; i++) {
                where['$or'].push({ _id: mg.ObjectID(_idlist[i]) })
            }
        }
        console.log(where)
        await mg.update('team_users', where, { $set: update })
        pu.success('OK', '', res)
        return
    }

    /*查询组织下所有人员*/
    async find_team_user (req, res, next) {
        var _id = req.body._id
        var duties_id = req.body.duties_id //岗位id
        var department_id = req.body.department_id //部门ID
        var pageSize = req.body.pageSize
        var last_page_id = req.body.last_page_id
        var text = req.body.text
        var dowload = req.body.dowload

        var where = {
            team_id: mg.ObjectID(req.headers.team),
            on_the_job: 0
        }
        if (_id) {
            let userinfo = await mg.findOne('team_users', { _id: mg.ObjectID(_id) })

            pu.success('OK', [userinfo], res, dowload, '员工信息', ex.team_user_download)
            return
        }
        if (department_id) {

            where.department_id = mg.ObjectID(department_id)
        }
        if (last_page_id) {
            where['_id'] = { $gt: mg.ObjectID(last_page_id) }
        }
        if (text) {
            if (isNaN(text) || text.length != 11) {
                where.name = { $regex: text }
            } else {
                where.phone = Number(text)
            }
        }
        if (pageSize && isNaN(pageSize)) {
            pu.fail('页数不正确', res)
            return
        }
        if (pageSize && !last_page_id) {
            let userinfo = await mg.find('team_users', where, {}, 0, Number(pageSize), {}, true)
            var resdata = {
                data: userinfo[0],
                allsum: userinfo[1]
            }
            pu.success('OK', resdata, res, dowload, '员工信息', ex.team_user_download)
            return
        } else {
            let userinfo
            if (last_page_id) {
                userinfo = await mg.find('team_users', where, {}, 0, Number(pageSize))
            } else {
                userinfo = await mg.find('team_users', where, {})
            }
            pu.success('OK', userinfo, res, dowload, '员工信息', ex.team_user_download)
            return
        }
    }

    /*直接新增人员*/
    async invitation_join (req, res, next) {
        var name = req.body.name
        var phone = req.body.phone
        var department_id = req.body.department_id // 部门ID
        var job_number = req.body.job_number //工号
        var dutiesinfo_id = req.body.dutiesinfo_id //岗位id
        var desc = req.body.desc //岗位id
        var residential_address = req.body.residential_address //居住地址
        var leader_name = req.body.leader_name //直属领导名称
        var leader_id = req.body.leader_id //直属领导id

        let isnull = pu.isnull([name, phone])
        if (isnull) {
            pu.fail('参数不正确', res)
            return
        }
        let userinfo = await mg.findOne('users', { phone: Number(phone) })
        var isreg = 0
        if (userinfo) {
            let info = await mg.findOne('team_users', { userid: userinfo._id })
            if (info) {
                pu.fail('已经在该组织', res)
                return
            }
            isreg = 1
        } else {
            let uinfo = await mg.findOne('team_users', { phone: Number(phone) })
            if (uinfo) {
                pu.fail('已经在该组织', res)
                return
            }

        }

        let teaminfo = await mg.findOne('team', { _id: mg.ObjectID(req.headers.team) })
        if (!teaminfo) {
            pu.fail('ID不正确', res)
            return
        }

        if (teaminfo.use_auth_sum >= teaminfo.auth_sum) {
            pu.fail('已经在该组织人数已经上限', res)
            return
        }

        var department = {
            department_name: '',
            department_id: ''
        }
        if (department_id) {
            let deinfo = await mg.findOne('department', { _id: mg.ObjectID(department_id) })
            if (deinfo) {
                department.department_name = deinfo.name
                department.department_id = deinfo._id
            } else {
                pu.fail('部门ID不正确', res)
                return
            }
        }
        var dutiesinfo = {
            duties_name: '',
            duties_id: ''
        }
        if (dutiesinfo_id) {
            let duinfo = await mg.findOne('dutiesinfo', { _id: mg.ObjectID(dutiesinfo_id) })
            if (duinfo) {
                dutiesinfo.duties_name = duinfo.name
                dutiesinfo.duties_id = duinfo._id
            } else {
                pu.fail('部门ID不正确', res)
                return
            }
        }

        let team_userinfo = {
            name: name,
            leader_name: leader_name,
            leader_id: leader_id, //
            userid: userinfo ? userinfo._id : '',
            job_number: job_number, // 员工编号
            id_no: userinfo ? userinfo.id_no : '',//身份证号码
            residential_address: residential_address,//居住地址
            phone: userinfo ? Number(userinfo.phone) : Number(phone),
            // department_name: department.department_name, //部门ID
            department_id: department.department_id,
            // team_name: teaminfo.team_name, //团队
            team_id: teaminfo._id,
            // duties_name: dutiesinfo.duties_name,//岗位
            duties_id: dutiesinfo.duties_id,//岗位id
            isreg: isreg,//是否注册 1注册 0未注册
            on_the_job: 0 //0在职 1离职
            , desc: desc//备注
            , role_id: ''
            , entry_time: new Date().getTime() //创建日期
        }
        /*组织新增人员*/
        let inser = await mg.insertOne('team_users', team_userinfo)
        /*同步组织表*/
        await mg.updateOne('team', { _id: mg.ObjectID(req.headers.team) }, { $inc: { use_auth_sum: 1 } })
        team_userinfo._id = inser.insertedId
        if (team_userinfo.id_no) {
            team_userinfo.id_no = '**** **** **** ' + team_userinfo.id_no.split(team_userinfo.id_no.length - 4, team_userinfo.id_no)
        }
        /*同步用户表*/
        if (userinfo) {
            if (userinfo.group_list && userinfo.group_list.length) {
                await  mg.updateOne('users', { _id: userinfo._id }, { $push: { group_list: teaminfo._id } })
            } else {
                await mg.updateOne('users', { _id: userinfo._id }, {
                    $push: { group_list: teaminfo._id },
                    $set: { last_group_id: team_userinfo._id, last_group_name: teaminfo.team_name }
                })
            }
        }
        pu.success('OK', team_userinfo, res)

    }

    /*同意加入公司*/
    async agree_join (req, res, next) {
        var _id = req.body._id // 公司id
        let isnull = pu.isnull([_id])
        if (isnull) {
            pu.fail('参数不正确', res)
            return
        }
        /***
         * 1、查询用户信息
         * 2、查询公司信息
         * 3、组合生成新信息插入新表
         */
        let userid = req.headers.userid

        let info = await mg.findOne('team_users', { team_id: mg.ObjectID(_id), userid: mg.ObjectID(userid) })
        if (info) {
            pu.fail('已经在该组织', res)
            return
        }
        let userinfo = await mg.findOne('users', { _id: mg.ObjectID(userid) })
        let teaminfo = await mg.findOne('team', { _id: mg.ObjectID(_id) })
        if (!teaminfo) {
            pu.fail('ID不正确', res)
            return
        }
        if (teaminfo.use_auth_sum >= teaminfo.auth_sum) {
            pu.fail('已经在该组织人数已经上限', res)
            return
        }
        let team_userinfo = {
            name: userinfo.name,
            userid: userinfo._id,
            leader_id: '',
            leader_name: '',
            job_number: '', // 员工编号
            id_no: userinfo.id_no || '',//身份证号码
            residential_address: '',//居住地址
            phone: userinfo.phone,
            // department_name: "", //部门ID
            department_id: '',
            // team_name: teaminfo.team_name, //团队
            team_id: teaminfo._id,
            // duties_name: "",//岗位
            duties_id: '',//岗位id
            isreg: 1,//是否注册 1注册 0未注册
            on_the_job: 0 //0在职 1离职
            , desc: ''//备注
            , role_id: ''
            , entry_time: new Date().getTime()
        }
        /*组织新增人员*/
        let inser = await mg.insertOne('team_users', team_userinfo)
        /*同步组织表*/
        await mg.updateOne('team', { _id: mg.ObjectID(_id) }, { $inc: { use_auth_sum: 1 } })
        team_userinfo._id = inser.insertedId
        if (team_userinfo.id_no) {
            team_userinfo.id_no = '**** **** **** ' + team_userinfo.id_no.split(team_userinfo.id_no.length - 4, team_userinfo.id_no)
        }
        delete team_userinfo.phone

        /*同步用户表*/
        if (userinfo.group_list && userinfo.group_list.length) {

            await  mg.updateOne('users', { _id: mg.ObjectID(userid) }, {
                $push: { group_list: teaminfo._id },
                $set: { last_group_id: teaminfo._id, last_group_name: teaminfo.team_name }
            })
        } else {
            await mg.updateOne('users', { _id: mg.ObjectID(userid) }, {
                $push: { group_list: teaminfo._id },
                $set: { last_group_id: teaminfo._id, last_group_name: teaminfo.team_name }
            })
        }
        pu.success('OK', team_userinfo, res)
    }

    /*作废邀请链接*/
    async delete_linkinfo (req, res, next) {
        var link = req.body.link
        let isnull = pu.isnull([link])
        if (isnull) {
            pu.fail('参数不正确', res)
            return
        }
        try {
            let resinfo = pu.decryption(decodeURIComponent(link))
            if (resinfo) {
                resinfo = JSON.parse(resinfo)
                await redis.set('INVITATION_LINK_' + +resinfo.team_id, '', 1)
                pu.success('OK', '', res)
            }
        } catch (e) {
            console.error(e)
            pu.fail('加密参数错误', res)
            return
        }
    }

    /*删除*/
    async delete_dutiesinfo (req, res, next) {
        let _id = req.body._id
        let isnull = pu.isnull([_id])
        if (isnull) {
            pu.fail('参数不正确', res)
            return
        }
        let info = await mg.findOne('team_users', { department_id: mg.ObjectID(department_id) })
        if (info) {
            pu.fail('部门下还有人员', res)
            return
        } else {
            await mg.updateOne({ _id: mg.ObjectID(department_id) })
            pu.fail('OK', res)
            return
        }
    }

    /*新增岗位*/
    async add_dutiesinfo (req, res, next) {
        var name = req.body.name
        var team_id = req.headers.team
        let isnull = pu.isnull([name, team_id])
        if (isnull) {
            pu.fail('参数不正确', res)
            return
        }
        let postinfo = {
            name: name,
            team_id: mg.ObjectID(team_id),
        }

        let inserinfo = await mg.insertOne('dutiesinfo', postinfo)
        postinfo._id = inserinfo.insertedId
        pu.success('OK', postinfo, res)
    }

    /*编辑岗位*/
    async update_dutiesinfo (req, res, next) {
        var name = req.body.name
        var _id = req.body._id
        let isnull = pu.isnull([_id])
        if (isnull) {
            pu.fail('参数不正确', res)
            return
        }
        await mg.updateOne('dutiesinfo', { _id: mg.ObjectID(_id) }, { $set: { name: name } })
        pu.success('OK', '', res)
    }

    /*查询岗位*/
    async find_dutiesinfo (req, res, next) {
        var _id = req.body._id
        var team_id = req.headers.team
        var where = {
            team_id: mg.ObjectID(team_id)
        }
        if (_id) {
            where._id = mg.ObjectID(_id)
        }

        let info = await mg.find('dutiesinfo', where)
        pu.success('OK', info, res)
    }

    /*统一返回链接*/
    async all_get_linkinfo (id, res) {
        let info = await mg.findOne('team', { _id: mg.ObjectID(id) })
        pu.success('OK', info, res)
    }

    /*通过组织ID查询邀请链接*/
    async get_link (req, res, next) {
        var _id = req.body._id
        var link = await redis.get('INVITATION_LINK_' + _id)
        pu.success('OK', link, res)
    }

    /*通过邀请链接查询组织信息*/
    async get_linkinfo (req, res, next) {
        var link = req.query.link
        console.log(link)
        let isnull = pu.isnull([link])
        if (isnull) {
            pu.fail('参数不正确', res)
            return
        }
        try {
            let resinfo = pu.decryption(decodeURIComponent(link))

            if (resinfo) {
                resinfo = JSON.parse(resinfo)

                if (resinfo.type == 0) { //一次性
                    let h_info = await redis.get('INVITATION_LINK_' + resinfo.team_id)
                    if (!h_info) {
                        pu.fail('链接已过期', res)
                    } else {
                        await redis.set('INVITATION_LINK_' + +resinfo.team_id, '', 1)
                        this.all_get_linkinfo(resinfo.team_id, res)
                    }
                }
                if (resinfo.type == 1) { //时间性
                    let h_info = await redis.get('INVITATION_LINK_' + +resinfo.team_id)
                    if (!h_info) {
                        pu.fail('链接已过期', res)
                    } else {
                        this.all_get_linkinfo(resinfo.team_id, res)
                    }
                }
                if (resinfo.type == 2) { //永久性
                    this.all_get_linkinfo(resinfo.team_id, res)
                }
            } else {
                pu.fail('加密参数错误', res)
            }
        } catch (e) {
            console.error(e)
            pu.fail('加密参数错误', res)
            return
        }
    }

    /*获取邀请链接*/
    async get_invitation_link (req, res, next) {
        let _id = req.body._id //公司id
        let type = req.body.type //0 一次性 1定期 2永久
        let timeout = req.body.time//过期时间 单位秒
        let isnull = pu.isnull([_id, type])
        if (isnull) {
            pu.fail('参数不正确', res)
            return
        }
        var team_info = await mg.findOne('team', { _id: mg.ObjectID(_id) })
        if (!team_info) {
            pu.fail('组织不正确', res)
            return
        }
        if (type == 0) {
            var info = {
                type: 0,
                team_id: team_info._id.toString(),
                team_name: team_info.team_name,
                redam: Math.random()
            }
            let resinfo = pu.encryption(JSON.stringify(info))

            await redis.set('INVITATION_LINK_' + _id, resinfo)
            pu.success('OK', encodeURIComponent(resinfo), res)
        }
        if (type == 1) {
            var info = {
                type: 1,
                team_id: team_info._id.toString(),
                team_name: team_info.team_name,
                redam: Math.random()
            }
            let resinfo = pu.encryption(JSON.stringify(info))
            await redis.set('INVITATION_LINK_' + _id, resinfo, timeout)
            pu.success('OK', encodeURIComponent(resinfo), res)
        }
        if (type == 2) {
            var info = {
                type: 2,
                team_id: team_info._id.toString(),
                team_name: team_info.team_name,
                redam: Math.random()
            }
            let resinfo = pu.encryption(JSON.stringify(info))
            await redis.set('INVITATION_LINK_' + _id, resinfo, timeout)

            pu.success('OK', encodeURIComponent(resinfo), res)
        }
    }

    /*删除部门*/
    async delete_department (req, res, next) {
        var _id = req.body._id
        let isnull = pu.isnull([_id])
        if (isnull) {
            pu.fail('参数不正确', res)
            return
        }

        var info = await mg.findOne('team_user', { department_id: mg.ObjectID(_id) })
        var last = await mg.findOne('department', { last_id: mg.ObjectID(_id) })

        if (last) {
            pu.fail('请先删除子部门', res)
            return
        }
        if (info) {
            pu.fail('部门下还有人员 不能删除', res)
            return
        } else {
            await mg.deleteOne('department', { _id: mg.ObjectID(_id) })
            pu.success('OK', '', res)

        }
    }

    /*查询部门*/
    async find_department (req, res, next) {
        var teamid = req.headers.team
        var info = await mg.find('department', { team_id: mg.ObjectID(teamid) })
        pu.success('OK', info, res)
    }

    /*编辑部门*/
    async update_department (req, res, next) {
        var _id = req.body._id
        var depart_name = req.body.depart_name
        var last_id = req.body.last_id
        var admin_id = req.body.admin_id
        var admin_name = req.body.admin_name
        var desc = req.body.desc
        // var director_name = req.body.director_name //主管名字
        // var director_id = req.body.director_id //主管id

        let isnull = pu.isnull([_id])
        if (isnull) {
            pu.fail('参数不正确', res)
            return
        }
        var where = {}
        if (depart_name) {
            where.depart_name = depart_name
        }
        if (desc) {
            where.desc = desc
        }
        /*获取上一个部门*/
        if (last_id) {
            var last_de_info = await mg.findOne('department', { _id: mg.ObjectID(last_id) })
            if (last_de_info) {
                where.last_id = last_de_info._id
                where.last_name = last_de_info.depart_name
            }
        }
        if (admin_id) {
            where.admin_id = mg.ObjectID(admin_id)
            where.admin_name = admin_name
        }
        await mg.updateOne('department', { _id: mg.ObjectID(_id) }, { $set: where })
        pu.success('编辑成功', '', res)
        return
    }

    /*新增部门*/
    async add_department (req, res, next) {
        var name = req.body.name   //名称
        var team_id = req.headers.team //团队id
        var last_id = req.body.last_id //上个部门id
        var admin_id = req.body.admin_id //管理员id
        var admin_name = req.body.admin_name //管理员id
        var desc = req.body.desc //部门介绍
        // var director_name = req.body.director_name //主管名字
        // var director_id = req.body.director_id //主管id
        let isnull = pu.isnull([name])
        if (isnull) {
            pu.fail('参数不正确', res)
            return
        }
        var teaminfo = await mg.findOne('team', { _id: mg.ObjectID(team_id) })
        if (!teaminfo) {
            pu.fail('团队id不正确', res)
            return
        }
        var lastinfo = {
            last_id: '',
            last_name: '',
        }
        if (last_id) {
            var last_de_info = await mg.findOne('department', { _id: mg.ObjectID(last_id) })

            if (last_de_info) {
                lastinfo.last_id = last_de_info._id
                lastinfo.last_name = last_de_info.depart_name
            }
        }
        var inserinfo = {
            depart_name: name, //部门名称
            last_id: lastinfo.last_id,//上级id
            last_name: lastinfo.last_name, //上级名称
            team_id: teaminfo._id, //组织id
            team_name: teaminfo.team_name, //组织名称
            admin_id: mg.ObjectID(admin_id), //
            admin_name: admin_name, //
            desc: desc,//组织名称
            // director_id: ""//主管id

        }
        let add_delinfo = await mg.insertOne('department', inserinfo)
        inserinfo._id = add_delinfo.insertedId
        console.log()
        pu.success('OK', inserinfo, res)
    }

    /*查询团队*/
    async find_team_info (req, res, next) {

        let _id = req.body._id //传id查询单个团队信息 不传查询全部团队

        var where = {}
        if (_id) {

            if (typeof _id == 'object') {
                where['$or'] = []
                for (var i = 0; i < _id.length; i++) {
                    where['$or'].push({ _id: mg.ObjectID(_id[i]) })
                }
                let team_info = await mg.find('team', where, { phone: 0, jur: 0 })
                pu.success('OK', team_info, res)
            } else {
                where._id = mg.ObjectID(_id)
                let team_info = await mg.findOne('team', where)
                pu.success('OK', team_info, res)
            }

            return
        }

        let userinfo = await mg.findOne('users', { _id: mg.ObjectID(req.headers.userid) })

        var where = []

        for (var i = 0; i < userinfo.group_list.length; i++) {
            where.push({ _id: userinfo.group_list[i] })
        }
        let teamlist = await mg.find('team', { $or: where }, { phone: 0, jur: 0 })
        pu.success('OK', teamlist, res)
    }

}


module.exports = new team()
